/**
 * CAINIAO打印
 * @param {Array} printData   必传  要打印的数据
 * @param {Sting} parcelType  必传  哪家快递，比如，EMS、圆通、申通、顺丰等
 * @param {Function} cb       选传  打印成功后执行的回调
 */
import { Message } from 'element-ui'
import { getPrintTemplate, printCount } from '@/api/outStorage'

export default function printEMSExpress(printData, parcelType, cb) {
  if (!Array.isArray(printData)) throw new Error('printEMSExpress方法第一个参数传入的数据不是array类型')
  if (cb) {
    const isFun = Object.prototype.toString.call(cb) === '[object Function]'
    if (!isFun) {
      throw new Error('printEMSExpress方法第三个参数必须传入函数！')
    }
  }
  let socket = ''
  let printNum = 0
  let standard = null // 标准模板地址
  let custom = null // 自定义模板地址

  // 开始打印
  const startPrinting = (printObject) => {
    console.log('即将打印的数据---->', JSON.stringify(printObject))
    socket.send(JSON.stringify(printObject))
    socket.onmessage = (res) => {
      const printResult = JSON.parse(res.data)
      if (printResult.cmd === 'print' && printResult.status === 'failed') {
        Message.error({ message: printResult.msg })
      }
      if (printResult.cmd === 'print' && printResult.status === 'success') {
        ++printNum
        if (printNum === printData.length) {
          cb && cb({ type: 'success', msg: '打印任务成功执行完毕' })
          Message.success({ message: '打印任务成功执行完毕' })
          socket.close()
        }
        // 面单打印次数
        printCount(printData[printNum - 1].code)
      }
      printResult.cmd === 'print' && console.log('打印结果---->', res.data)
    }
  }

  // 处理要打印的数据
  const processingData = () => {
    for (const item of printData) {
      const documents = []
      const printObject = {
        cmd: 'print',
        requestID: new Date().getTime(),
        version: '1.0',
        task: {
          taskID: getUUID(8, 10),
          preview: false,
          printer: '',
          notifyMode: 'allInOne',
          previewType: 'pdf',
          documents: []
        }
      }
      const result = item.printData ? JSON.parse(item.printData) : null
      if (result && result.templateURL) {
        standard = result.templateURL
        custom = item.templateUrl
      }
      const expressBillData = {
        documentID: item.code,
        contents: [
          {
            data: {
              recipient: {
                address: {
                  detail: item.receiverDetailAddress
                  // city: item.receiverCity,
                  // detail: item.receiverDetailAddress,
                  // district: item.receiverDistrict,
                  // province: item.receiverProvince,
                  // town: item.receiverTown || ''
                },
                mobile: item.receiverMobile,
                name: item.receiverName,
                phone: ''
              },
              routingInfo: result ? result.data.routingInfo : {},
              sender: {
                address: {
                  city: item.senderCity,
                  detail: item.senderDetailAddress,
                  district: item.senderDistrict,
                  province: item.senderProvince,
                  town: item.senderTown || ''
                },
                mobile: item.senderMobile,
                name: item.senderName,
                phone: ''
              },
              waybillCode: item.waybillCode
            },
            templateURL: standard
            // templateURL: 'http://cloudprint.cainiao.com/template/standard/345208/4'
          }
        ]
      }

      const arr = []
      const goodsContent = []
      const inherentProject = [{
        lable: '编码',
        value: 'goodCode'
      }, {
        lable: '名称',
        value: 'goodsName'
      }, {
        lable: '规格',
        value: 'spec'
      }, {
        lable: '数量',
        value: 'quantity'
      }, {
        lable: '条码',
        value: 'goodsBarCode'
      }]
      item.deliveryItemVOList.forEach(goods => {
        for (const project of inherentProject) {
          if (project.value === 'quantity') {
            goodsContent.push(`${goods[project.value]}*${goods.goodsUnitName}`)
          } else {
            if (goods[project.value] !== '') {
              goodsContent.push(goods[project.value])
            }
          }
        }
      })
      arr.push(goodsContent.join(' '))

      const customContent = arr.filter((s) => s)

      const info = {
        data: {
          info: `${customContent.join('，')}`
        },
        templateURL: custom
        // templateURL: 'http://cloudprint.cainiao.com/template/customArea/14012516/7'
      }

      info.data.wavePickingCode = `波次号：${item.wavePickingCode}`
      info.data.orderNum = `打印顺序：${item.orderNum || ''}`
      info.data.source = `订单来源：${item.sourcePlatformName || ''}`
      expressBillData.contents.push(info)
      documents.push(expressBillData)
      printObject.task.documents = documents
      startPrinting(printObject)
    }
  }
  // 设置打印机配置
  const setPrinterConfig = (defaultPrinter) => {
    const parms = {
      cmd: 'setPrinterConfig',
      requestID: getUUID(8, 10),
      version: '1.0',
      printer: {
        name: defaultPrinter,
        needTopLogo: false,
        needBottomLogo: false,
        horizontalOffset: 0.5,
        verticalOffset: 0.7,
        forceNoPageMargins: true,
        autoPageSize: true,
        orientation: 0,
        autoOrientation: false,
        paperSize: {
          width: 100,
          height: 180
        }
      }
    }
    socket.send(JSON.stringify(parms))
    processingData()
  }

  // 获取打印机列表
  const getPrinters = () => {
    const parms = {
      cmd: 'getPrinters',
      requestID: getUUID(8, 10),
      version: '1.0'
    }
    socket.send(JSON.stringify(parms))
    socket.onmessage = (e) => {
      const data = JSON.parse(e.data)
      data.defaultPrinter && setPrinterConfig(data.defaultPrinter)
    }
  }

  // 初始化WebSocket
  const initsocket = () => {
    socket = new WebSocket('ws://localhost:13528')
    // 建立连接
    socket.onopen = e => {
      console.log('Socket连接成功--->', e)
      getPrinters()
    }
    // 接受服务器返回的信息
    socket.onmessage = e => {
      console.log('received--->', e.data)
    }
    // 关闭连接
    socket.onclose = e => {
      console.warn('socket连接已关闭--->', e)
    }
    // 连接错误
    socket.onerror = e => {
      Message.error({ message: '无法打印，请打开《CAINIAO打印组件》重试！' })
      console.error('socket连接发生错误--->', e)
      cb && cb({ type: 'failed', msg: '无法打印，请打开《CAINIAO打印组件》重试！' })
    }
  }

  // 获取请求的UUID，指定长度和进制，如 getUUID(8, 2)   //"01001010" 8 character (base=2)
  const getUUID = (len, radix) => {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
    var uuid = []; var i
    radix = radix || chars.length
    if (len) {
      for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]
    } else {
      var r
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
      uuid[14] = '4'
      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random() * 16
          uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r]
        }
      }
    }
    return uuid.join('')
  }

  // 获取标准模板
  const getStandardTpl = new Promise((resolve, reject) => {
    getPrintTemplate({ type: 0, code: parcelType }).then(res => {
      const data = res.data.filter(item => Number(item.standardWaybillType) === 6)
      standard = data[0].standardTemplateUrl
      resolve(data)
    })
  })
  // 获取自定义模板
  const getCustomTpl = new Promise((resolve, reject) => {
    getPrintTemplate({ type: 1, code: 'zdy' }).then(res => {
      const data = res.data.filter(item => Number(item.standardWaybillType) === 4)
      custom = data[0].standardTemplateUrl
      resolve(data)
    })
  })
  Promise.all([getStandardTpl, getCustomTpl])
    .then((result) => {
      initsocket()
    })
    .catch((error) => {
      console.log(error)
    })
}
